﻿using System;
using System.Net.Mail;
using System.IO;
using CDO;

namespace DotNetNexusSpam.SpamFilter
{
    class AttachmentExtensionFilter : FilterBase
    {
        public AttachmentExtensionFilter(CDOMessageWrapper email, string startupPath)
            : base(email, startupPath)
        {
            base.Name = "Attachement extensions";
        }

        public override void Fire()
        {
            base.ActionToTake = FilterAction.PROCESS_NORMALLY;
            base.IsSpam = false;

            foreach (IBodyPart attach in Email.CDOMessage.Attachments) {
                foreach (string ext in _extensionsList) {
                    if (attach.FileName.EndsWith(ext))
                    {
                        base.ActionToTake = FilterAction.DELETE_EMAIL;
                        base.IsSpam = true;
                    }
                }
            }
        }

        /// <summary>
        /// The file extension filter will delete any emails with the file attachment extensions that are 
        /// loaded from the extensions.txt file. 
        /// </summary>
        private const string EXTENSIONS = "extensions.txt";
        private string[] _extensionsList;
        public override void LoadConfiguration()
        {
            string settingsPath = base.StartupPath + "config\\" + EXTENSIONS;
            if (File.Exists(settingsPath))
            {
                string extensionContent = "";
                using (StreamReader settingsReader = new StreamReader(settingsPath))
                {
                    extensionContent = settingsReader.ReadToEnd();
                }
                _extensionsList = extensionContent.Split(new string[] { Environment.NewLine }, StringSplitOptions.None);
                _log.Debug("Extensions file was loaded succesfully.");
            }
            else
            {
                _log.Warn("Extensions file could not be loaded from " + settingsPath);
            }
        }
    }
}
